// Created by Joe on 2017/6/12.

app.controller(
    'ProfileController',
    [
        'KEY', 'config', '$scope', '$timeout', '$interval', '$location', 'UserService', 'ProfileService',
        function (KEY, config, $scope, $timeout, $interval, $location, UserService, ProfileService) {
            init();

            function init() {
                // set move
                $scope.position = config.Profile;

                // set page
                $scope.page = [
                    'login', 'register', 'find-password', 'personal-center',
                    'change-password', 'user-certification'
                ];

                // page and panel control
                $scope.control = {page: 0, panel: 0, keyboard: false, verLock: false, hold: 0};
                if (!UserService.user.phone) {
                    // not login
                } else {
                    $scope.control.page = 3;
                    $scope.control.panel = UserService.user.certification ? 1 : 0;
                }
                // toast show and toast info
                $scope.panel = {show: false, info: '', load: false};

                // current position
                $scope.cp = $scope.position[$scope.page[$scope.control.page]];

                // set page stack
                $scope.pageStack = [];

                // set focus
                $scope.focus = {
                    // current id
                    ci: $scope.cp[$scope.control.page !== 3 ? 0 : $scope.control.panel === 0 ? 0 : 3].id,
                    hold: ''
                };

                // set input handler
                $scope.ele = '';

                // set timer
                $scope.timer = null;

                // info display
                $scope.display = {
                    name: '',
                    phone: '',
                    password: '',
                    password_temp: '',
                    verCode: '',
                    card: '',
                    genVerCode: ''
                };
                $scope.userRef = UserService.user;

                // set info <-> input map
                $scope.infoMap = {
                    'login': [
                        {name: 'phone', id: ['fp-1', 'pp-1']},
                        {name: 'verCode', id: ['fp-3']},
                        {name: 'password', id: ['pp-2']}
                    ],
                    'register': [
                        {name: 'phone', id: ['up-1']},
                        {name: 'verCode', id: ['up-3']},
                        {name: 'password', id: ['pp-1']}
                    ],
                    'find-password': [
                        {name: 'phone', id: ['up-1']},
                        {name: 'verCode', id: ['up-3']},
                        {name: 'password', id: ['pp-1']}
                    ],
                    'change-password': [
                        {name: 'password_temp', id: ['pp-3']},
                        {name: 'password', id: ['pp-1', 'fp2-1']},
                        {name: 'verCode', id: ['fp1-2']}
                    ],
                    'user-certification': [
                        {name: 'name', id: ['up-1']},
                        {name: 'card', id: ['up-2']}
                    ]
                };

                // add profile logic
                addLogic();

                // ele action
                $scope.move = function (evt, cb) {
                    $scope.ele = evt.target;
                    evt.preventDefault();
                    switch (evt.keyCode) {
                        case KEY.LEFT:
                            moveShim('left');
                            if (evt.target.id === 'pp')
                                panelSwitch();
                            break;
                        case KEY.UP:
                            moveShim('up');
                            break;
                        case KEY.RIGHT:
                            moveShim('right');
                            if (evt.target.id === 'fp')
                                panelSwitch(1, 6);
                            break;
                        case KEY.DOWN:
                            moveShim('down');
                            break;
                        case KEY.ENTER:
                            if ($scope.ele.tagName.toLowerCase() === 'input') {
                                $scope.ele.style.border = '2px solid #46a7e7';
                                $scope.ele.style.opacity = '1';
                                $('.city__profile-separator').css('margin-top', '-80px');
                                $('.city__profile-content').css('margin-top', '-80px');
                                inputFlag = true;
                                $scope.control.keyboard = true;
                                save_old_index();
                                change_components(0, 0, keyboardArray);
                                $timeout(function () {
                                    $("#keyboard_a").focus();
                                });
                            } else {
                                cb instanceof Function && cb();
                            }
                            break;
                    }
                };

                // global action
                document.addEventListener('keydown', handlePS);
            }

            // profile logic
            function addLogic() {
                // set user
                function resetUserInfo(info) {
                    UserService.user.name = info.custName;
                    UserService.user.card = info.idCard;
                    UserService.user.phone = info.mobilePhone;
                    UserService.user.nickName = info.nickName;
                    UserService.user.certification = info.isRealName !== '0';
                }

                $scope.gotoRegister = pageSwitch(1);
                $scope.gotoFindPassword = pageSwitch(2);
                $scope.gotoChangePassword = pageSwitch(4);
                $scope.gotoUserCertification = pageSwitch(5);
                $scope.logout = function () {
                    UserService.user = {};
                    $location.path('/home').replace();
                };

                // generate verify-code
                $scope.generateVerCode = function (type) {
                    return function () {
                        var curPhone = UserService.user.phone ? UserService.user.phone : $scope.display.phone;

                        if (curPhone.length !== 11) {
                            $scope.panel.info = '手机号长度不足';
                            $scope.panel.show = true;
                            return;
                        }

                        if ($scope.control.verLock) {
                            $scope.panel.info = '操作频繁，请稍后再试';
                            $scope.panel.show = true;
                            return;
                        }

                        $scope.control.verLock = true;
                        var ele = document.activeElement, num = 59;
                        $scope.timer = $interval(function () {
                            ele.innerText = '( ' + num-- + ' )';
                            if (num === 0) {
                                $scope.control.verLock = false;
                                $interval.cancel($scope.timer);
                                ele.innerText = '获取验证码';
                            }
                        }, 1000);

                        ProfileService.generateVerCode(curPhone, type)
                            .then(function (info) {
                                if (info.error) {
                                    $scope.panel.info = info.error.error || '获取验证码失败';
                                    $scope.panel.show = true;
                                    $scope.control.verLock = false;
                                    $interval.cancel($scope.timer);
                                    ele.innerText = '获取验证码';
                                }
                            });
                    };
                };

                // switch, success if isVerify is false or value-code is '1'
                $scope.next = function (pos, isVerify, type) {
                    return function () {
                        if (isVerify) {
                            $scope.panel.load = true;
                            var curPhone = UserService.user.phone ? UserService.user.phone : $scope.display.phone;
                            ProfileService.verCodeCheck(curPhone, $scope.display.verCode, type)
                                .then(function (info) {
                                    $scope.panel.load = false;
                                    if (info.valueCode === '1') {
                                        panelSwitch($scope.control.panel + 1, pos);
                                    } else {
                                        $scope.panel.info = info.msg || '验证失败';
                                        $scope.panel.show = true;
                                    }
                                });
                        } else {
                            panelSwitch($scope.control.panel + 1, pos);
                        }
                    };
                };

                // login, success if value-code is '1'
                $scope.login = function () {
                    if ($scope.control.panel === 0) {
                        $scope.panel.load = true;
                        ProfileService.fastLogin($scope.display.phone, $scope.display.verCode)
                            .then(function (info) {
                                $scope.panel.load = false;
                                if (info.valueCode === '1') {
                                    ProfileService.getUserDetail()
                                        .then(function (user) {
                                            resetUserInfo(user);
                                            $location.path('/home').replace();
                                        });
                                    $scope.panel.info = '登录成功，即将返回首页';
                                } else {
                                    $scope.panel.info = info.msg || '登录失败';
                                }
                                $scope.panel.show = true;
                            });
                    } else {
                        $scope.panel.load = true;
                        ProfileService.passwordLogin($scope.display.phone, $scope.display.password)
                            .then(function (info) {
                                $scope.panel.load = false;
                                if (info.valueCode === '1') {
                                    ProfileService.getUserDetail()
                                        .then(function (user) {
                                            resetUserInfo(user);
                                            $location.path('/home').replace();
                                        });
                                    $scope.panel.info = '登录成功，即将返回首页';
                                } else {
                                    $scope.panel.info = info.msg || '登录失败';
                                }
                                $scope.panel.show = true;
                            });
                    }
                };

                // register, success if code is '0000'
                $scope.register = function () {
                    if ($scope.display.password.length < 6) {
                        $scope.panel.info = '密码长度不足';
                        $scope.panel.show = true;
                    } else {
                        $scope.panel.load = true;
                        ProfileService.register($scope.display.phone, $scope.display.password)
                            .then(function (info) {
                                $scope.panel.load = false;
                                if (info.code === '0000') {
                                    ProfileService.getUserDetail()
                                        .then(function (user) {
                                            resetUserInfo(user);
                                            $location.path('/home').replace();
                                        });
                                    $scope.panel.info = '注册成功，即将返回首页';
                                } else {
                                    $scope.panel.info = info.message || '注册失败';
                                }
                                $scope.panel.show = true;
                            });
                    }
                };

                // find password, success if code is '0000'
                $scope.findPassword = function () {
                    var curPhone = UserService.user.phone ? UserService.user.phone : $scope.display.phone;
                    if ($scope.display.password.length < 6) {
                        $scope.panel.info = '密码长度不足';
                        $scope.panel.show = true;
                    } else {
                        $scope.panel.load = true;
                        ProfileService.findPassword(curPhone, $scope.display.password)
                            .then(function (info) {
                                $scope.panel.load = false;
                                if (info.code === '0000') {
                                    $scope.panel.info = '密码修改成功，即将返回首页';
                                    $timeout(function () {
                                        $location.path('/home').replace();
                                    }, 3000);
                                } else {
                                    $scope.panel.info = info.message || '修改失败';
                                }
                                $scope.panel.show = true;
                            });
                    }
                };

                // change password, success if value-code is '1'
                $scope.changePassword = function () {
                    if ($scope.display.password.length < 6
                        || $scope.display.password_temp.length < 6) {
                        $scope.panel.info = '密码长度不足';
                        $scope.panel.show = true;
                    } else {
                        $scope.panel.load = true;
                        ProfileService.changePassword($scope.display.password, $scope.display.password_temp)
                            .then(function (info) {
                                $scope.panel.load = false;
                                if (info.valueCode === '1') {
                                    $timeout(function () {
                                        $location.path('/home').replace();
                                    }, 3000);
                                    $scope.panel.info = '密码修改成功，即将返回首页';
                                } else {
                                    $scope.panel.info = info.msg || '密码修改失败';
                                }
                                $scope.panel.show = true;
                            });
                    }
                };

                // certification, success if code is '0000'
                $scope.userCertification = function () {
                    if (!$scope.display.name) {
                        $scope.panel.info = '姓名不能为空';
                        $scope.panel.show = true;
                        return;
                    }

                    if ($scope.display.card.length < 18) {
                        $scope.panel.info = '身份证号位数不足';
                        $scope.panel.show = true;
                        return;
                    }

                    $scope.panel.load = true;
                    ProfileService.certification(UserService.user.phone, $scope.display.name, $scope.display.card)
                        .then(function (info) {
                            $scope.panel.load = false;
                            if (info.code === '0000') {
                                ProfileService.getUserDetail()
                                    .then(function (user) {
                                        resetUserInfo(user);
                                        $location.path('/home').replace();
                                    });
                                $scope.panel.info = '实名认证成功，即将返回首页';
                            } else {
                                $scope.panel.info = info.message || '验证失败';
                            }
                            $scope.panel.show = true;
                        });
                };
            }

            // page switch
            function pageSwitch(page, panel, pos) {
                page = page || 0;
                panel = panel || 0;
                return function () {
                    // shim
                    $scope.panel.load = false;
                    $scope.panel.show = false;
                    page !== 0 && ($scope.control.hold = 0);
                    if (page === 1) {
                        $scope.display.verCode = '';
                    }
                    // common
                    $scope.pageStack.push($scope.control.page);
                    $scope.control.page = page;
                    $scope.control.panel = panel;
                    $scope.cp = $scope.position[$scope.page[$scope.control.page]];
                    resetFocus(pos);
                };
            }

            // panel switch
            function panelSwitch(panel, pos) {
                panel = panel || 0;
                $scope.control.panel = panel;
                resetFocus(pos);
            }

            // reset focus
            function resetFocus(pos) {
                pos = pos || 0;
                $scope.focus.ci = $scope.cp[pos]['id'];
            }

            // focus move
            function moveShim(dir) {
                if ($scope.control.page === 0) {
                    if ($scope.focus.ci === 'fp' && dir === 'down') {
                        $scope.control.hold = 1;
                    } else if ($scope.focus.ci === 'pp' && dir === 'down') {
                        $scope.control.hold = 2;
                    }
                }

                var curFocus = $scope.cp.filter(function (item) {
                    return item.id === $scope.focus.ci;
                })[0];
                if (curFocus['move'][dir] !== -1) {
                    $scope.focus.ci = curFocus['move'][dir];
                }

                if ($scope.control.page === 0) {
                    if ($scope.focus.ci === 'fp' || $scope.focus.ci === 'pp') {
                        $scope.control.hold = 0;
                    }
                }
            }

            // handle page stack
            function handlePS() {
                event.preventDefault();
                if (event.keyCode === KEY.BACK && !$scope.control.keyboard) {
                    if ($scope.pageStack.length) {
                        $scope.panel.load = false;
                        $scope.panel.show = false;
                        $scope.control.page = $scope.pageStack.pop();
                        $scope.control.panel = $scope.control.page !== 3 ? 0 : UserService.user.certification ? 1 : 0;
                        $scope.cp = $scope.position[$scope.page[$scope.control.page]];
                        resetFocus($scope.control.page !== 3 ? 0 : $scope.control.panel === 0 ? 0 : 3);
                    } else {
                        $scope.$apply(function () {
                            $location.path('/home').replace();
                        });
                    }
                } else if (event.keyCode === KEY.ENTER && $scope.control.keyboard) {
                    if (inputFlag) {
                        var curInfoMap = $scope.infoMap[$scope.page[$scope.control.page]];
                        var curInput = curInfoMap.filter(function (item) {
                            var flag = false;
                            for (var i = 0; i < item.id.length; i++) {
                                if ($scope.ele.id === item.id[i]) {
                                    flag = true;
                                    break;
                                }
                            }
                            return flag;
                        })[0];

                        if (inputLetter) {
                            inputLetter = false;
                            if (curInput.name === 'phone') {
                                if ($scope.display.phone.length < 11
                                    && /[0-9]/.test(charContainer)) {
                                    $scope.display.phone += charContainer;
                                }
                            } else if (curInput.name === 'verCode') {
                                if ($scope.display.verCode.length < 4
                                    && /[0-9]/.test(charContainer)) {
                                    $scope.display.verCode += charContainer;
                                }
                            } else if (curInput.name === 'card') {
                                if ($scope.display.card.length < 18
                                    && /[0-9a-z]/i.test(charContainer)) {
                                    $scope.display.card += charContainer;
                                }
                            } else if (curInput.name === 'name') {
                                if ($scope.display.name.length < 8) {
                                    $scope.display.name += charContainer;
                                }
                            } else {
                                $scope.display[curInput.name] += charContainer;
                            }
                        }

                        if (document.activeElement.id === 'keyboard_dele') {
                            if ((isChinese && chineseSearch < 0)
                                || (!isChinese && $scope.display[curInput.name].length > 0)) {
                                $scope.display[curInput.name] =
                                    $scope.display[curInput.name].substr(0, $scope.display[curInput.name].length - 1);
                            }
                        }
                    } else {
                        $('.city__profile-separator').css('margin-top', '0');
                        $('.city__profile-content').css('margin-top', '0');
                        $scope.ele.style.border = '2px solid rgba(255, 255, 255, .1)';
                        $scope.ele.style.opacity = '.5';
                        $scope.ele.focus();
                        $scope.control.keyboard = false;
                    }
                }
                $scope.$digest();
            }

            $scope.$on('$destroy', function () {
                document.removeEventListener('keydown', handlePS);
                $scope.timer && $interval.cancel($scope.timer);
            });
        }
    ]
);